"""


"""
import time
from datetime import timedelta

from flask import current_app, jsonify
from flask import redirect
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News
from info.utils.response_code import RET
from . import admin_blu
from flask import render_template


@admin_blu.route("/login", methods=["GET", "POST"])
def admin_login():
    """
    渲染后台登陆页面
    处理登陆请求
    1、获取参数判空
    2、查询数据库， 看是否有该用户
    3、校验密码是否正确
    4、校验是否是管理员
    5、保存用户登陆信息到session
    6、登录成功重定向到管理员首页

    :return:
    """
    if request.method == "GET":
        # 我们既要确保能够获取到用户信息， 还要确保这个用户的登陆信息是管理员身份
        # 才能够直接从登陆页面跳转到后台首页
        user = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user and is_admin:
            return redirect(url_for("admin.admin_index"))

        return render_template("admin/login.html")

    # 1、获取参数判空
    data_dict = request.form
    username = data_dict.get("username")
    password = data_dict.get("password")
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数错误")

    # 2、查询数据库， 看是否有该用户
    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据库查询错误")

    if not user:
        return render_template("admin/login.html", errmsg="用户不存在")
    # 3、校验密码是否正确
    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="用户名或者密码错误")
    # 4、校验是否是管理员
    if not user.is_admin:
        return render_template("admin/login.html", errmsg="非管理员限制登录")
    # 5、保存用户登陆信息到session
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin
    # 6、登录成功重定向到管理员首页
    return redirect(url_for("admin.admin_index"))


@admin_blu.route("/index", methods=["GET", "POST"])
def admin_index():
    """后台首页展示"""
    return render_template("admin/index.html")


@admin_blu.route("/user_count")
def user_count():
    """用户统计展示"""
    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 月新增数量
    month_count = 0
    t = time.localtime()  # 返回当前系统时间的对象
    # 得到本月1号的字符串
    begin_mon_date_str = '%d-%02d-01' % (t.tm_year, t.tm_mon)
    # 把上面的字符串处理成datetime对象，才可以和User.create_time进行大小对比
    from datetime import datetime
    begin_mon_date = datetime.strptime(begin_mon_date_str, "%Y-%m-%d")
    try:
        # month_count = User.query.filter(User.is_admin==False, User.create_time > 本年本月01日00点00分00秒).count()
        month_count = User.query.filter(User.is_admin == False, User.create_time > begin_mon_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日新增数量
    day_count = 0
    begin_day_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    begin_day_date = datetime.strptime(begin_day_date_str, "%Y-%m-%d")
    try:
        # day_count = User.query.filter(User.is_admin==False, User.create_time > 本年本月本日00点00分00秒).count()
        day_count = User.query.filter(User.is_admin == False, User.create_time > begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)




    # 折线图处理

    active_count = []  # 活跃用户数量
    active_time = []  # 每一天时间点

    for i in range(0, 30):
        # 起始时间点
        begin_date = begin_day_date - timedelta(days=i)
        # 结束时间点
        end_date = begin_day_date - timedelta(days=(i-1))
        try:
            # day_count = User.query.filter(User.is_admin==False, 起始时间点 <= User.last_login < 结束时间点 ).count()
            # day_count = User.query.filter(User.is_admin==False,  User.last_login>=起始时间点,    User.last_login< 结束时间点 ).count()  # 这才是正确的格式
            cot = User.query.filter(User.is_admin == False,  User.last_login>=begin_date,    User.last_login < end_date).count()   # 当天的活跃数量
        except Exception as e:
            current_app.logger.error(e)

        active_count.append(cot)
        active_time.append(begin_date.strftime("%Y-%m-%d"))   # 把时间对象转换成字符串传给前端

    active_count.reverse()
    active_time.reverse()

    data = {
        "total_count": total_count,
        "month_count": month_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_time": active_time
    }

    return render_template("admin/user_count.html", data=data)


@admin_blu.route("/news_review")
def news_review():
    keywords = request.args.get("keywords")

    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 2、查询数据库分页查询
    cur_news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status==1]

    if keywords:
        filters.append(News.title.contains(keywords))

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        cur_news_list = paginate.items  # 当前页数据
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 3、新闻数据模型对象列表转换成字典列表
    cur_user_news_list = []
    for i in cur_news_list:
        cur_user_news_list.append(i.to_review_dict())

    # 4、返回数据 ：  新闻字典里列表、 总页数、当前页
    data = {
        "cur_user_news_list": cur_user_news_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_review.html", data=data)


@admin_blu.route("/news_review_detail/<int:news_id>")
def news_review_detail(news_id):
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return redirect(url_for('admin.news_review'))

    data = {
        "news": news.to_dict()
    }

    return render_template("admin/news_review_detail.html", data=data)


@admin_blu.route("/news_review_action", methods=["POST"])
def news_review_action():

    # 1. 接受参数(两个参数  new_id, action的值如果是accept就通过，如果是reject就拒绝通过，拒绝的情况下再获取一个参数reason)
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2. 参数校验
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3、查询新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")
    # 4、判断action的值进行 执行对应操作(修改news.status 通过为0，不通过为-1)

    if action == "accept":
        news.status = 0
    else:
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="缺少原因")

        news.status = -1
        news.reason = reason

    # 5、提交数据
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    # 6、返回数据
    return jsonify(errno=RET.OK, errmsg="操作成功")